﻿using AutoMapper;
using B.S.BasicData.Api.Write.Application.Command.GridType;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Application.Handler.GridType
{
    public class DelGridtypeHandler : IRequestHandler<DelGridtypeCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<GridTypeModel> gridTypeRepo;
        private readonly IMapper mapper;
        private readonly ILogger<DelGridtypeHandler> logger;

        public DelGridtypeHandler(IBaseRepository<GridTypeModel> gridTypeRepo, IMapper mapper,ILogger<DelGridtypeHandler> logger)
        {
            this.gridTypeRepo = gridTypeRepo;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(DelGridtypeCommand request, CancellationToken cancellationToken)
        {
            logger.LogInformation("您正在删除网格类型:"+request.Id);
            ApiResult<int> res = new ApiResult<int>();
            //根据id查找网格类型实体
            var gridTypeModel = await gridTypeRepo.GetModel(request.Id);
            if (gridTypeModel == null)
            {
                logger.LogError("您要删除的网格类型不存在:"+ request.Id);
                res.Msg = "您要删除的网格类型不存在!";
                res.Data = 0;
                res.Code = ApiEnum.Failed;
                return res;
            }


            //把请求命令对象转成网格类型实体
            gridTypeModel.IsDeleted = true;

            var r = await gridTypeRepo.UpdateAsync(gridTypeModel);
            if (r > 0)
            {
                res.Msg = "删除网格类型成功!";
                res.Code = ApiEnum.Success;
                res.Data = r;
            }
            else
            {
                res.Msg = "删除网格类型失败!";
                res.Code = ApiEnum.Failed;
                res.Data = r;
            }
            return res;

        }
    }
}
